package club.web51.classroominteractiontoolsadmin.Security;

import club.web51.classroominteractiontoolsadmin.DO.MainDO.User;
import club.web51.classroominteractiontoolsadmin.Enums.MsgEnum;
import club.web51.classroominteractiontoolsadmin.Exceptions.ErrDataException;
import club.web51.classroominteractiontoolsadmin.Repositories.UserRepository;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @Classname JwtUtil
 * @Description TODO jwt工具类
 * @Created by yln
 */
@Component
public class JwtUtil {
    @Resource
    UserRepository userRepository;
    @Resource
    JwtOperator jwtOperator;

    /**
     * 生成Token
     * @param user 用户
     * @return 加密的Token
     */
    public String sign(User user){
        HashMap<String, Object> objectHashMap = Maps.newHashMap();
        if(Objects.isNull(user.getUid())){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }
        objectHashMap.put("uid",""+user.getUid());
        objectHashMap.put("username",user.getUsername());

      return jwtOperator.generateToken(objectHashMap);
    };

    /**
     * 验证Token
     * @param token 令牌
     * @param uid 用户id
     * @param password 用户密码
     * @return 是否有效
     */
    public boolean verify(String token,Long uid,String password){
        if(!jwtOperator.validateToken(token)){
            return false;
        }else{
            Claims claims =  jwtOperator.getClaimsFromToken(token);
            Long uid2 = Long.getLong(claims.get("uid",String.class));
            if(!uid2.equals(uid)){
                return false;
            }
            User user = userRepository.getOne(uid2);
            if(user.getPassword().equals(password)){
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * 验证Token
     * @param token 令牌
     * @return 是否有效
     */
    public boolean verify(String token){
        if(!jwtOperator.validateToken(token)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 从token获取uid
     * @param token 令牌
     * @return 用户uid
     */
    public Long getUid(String token){
        String uid = (String) jwtOperator.getClaimsFromToken(token).get("uid");
        return Long.parseLong(uid);
    }



}
